package com.quectel.cms.controller.car;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.device.DeviceExtraAttrCls;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.car.dto.CarDto;
import com.quectel.core.module.car.dto.mongo.MongoCarAccessRecordDto;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.car.service.mongo.MongoCarAccessRecordService;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-17 16:01:41
 */
@RestController
@RequestMapping("carAccessRecord")
@Tag(name = "CarAccessRecordController", description = "车辆访问记录表相关api")
public class CarAccessRecordController extends BaseController {

    @DubboReference
    private MongoCarAccessRecordService carAccessRecordService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private CarService carService;

    @PostMapping("importExcel")
    @RequirePermissions(values = "carAccessRecord:importExcel")
    @Operation(summary = "车辆出入数据导入")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        final Long tenantId = SessionHolder.getSysUser().getTenantId();
        Date currentDate = new Date();
        int totalCount = 0;
        int successCount = 0;

        List<MongoCarAccessRecordDto> carAccessRecordDtos = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    totalCount += analysis.size();

                    Map<String, List<Map<Integer, String>>> groupByVillageName = analysis.stream().collect(Collectors.groupingBy(o -> o.get(0)));
                    for (String villageName : groupByVillageName.keySet()) {
                        VillageDto villageDto = villageService.selectCacheByName(tenantId, villageName);
                        if (villageDto == null) {
                            continue;
                        }

                        List<Map<Integer, String>> maps = groupByVillageName.get(villageName);
                        List<MongoCarAccessRecordDto> list = maps.stream().map(row -> {
                            String deviceUniqueId = row.get(1);
                            String license = row.get(2);
                            String licenseColor = row.get(3);
                            String carType = row.get(4);
                            String snapImage = row.get(5);
                            String accessTime = row.get(6);

                            DeviceDto deviceDto = deviceService.selectCacheByUniqueId(deviceUniqueId, tenantId);
                            if (deviceDto == null) {
                                return null;
                            }

                            CarDto carDto = carService.selectOne(villageDto.getId(), license
                                    , SysCodeUtils.easyToGetValue(SysCodeKeyConstants.LICENSE_COLOR, licenseColor, Byte.class));

                            DeviceExtraAttrCls.AttrOfIntelligentParkingGate attrOfIntelligentEntranceGuard = DeviceExtraAttrCls
                                    .parseExtStr(DeviceExtraAttrCls.AttrOfIntelligentParkingGate.class, deviceDto.getExtraAttr());

                            MongoCarAccessRecordDto carAccessRecordDto = new MongoCarAccessRecordDto();
                            carAccessRecordDto.setTenantId(tenantId);
                            carAccessRecordDto.setVillageId(villageDto.getId());
                            carAccessRecordDto.setDeviceCategoryId(deviceDto.getId());
                            carAccessRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                            carAccessRecordDto.setCarId(carDto == null ? null : carDto.getId());
                            carAccessRecordDto.setDeviceId(deviceDto.getId());
                            carAccessRecordDto.setDeviceName(deviceDto.getName());
                            carAccessRecordDto.setLicense(license);
                            carAccessRecordDto.setLicenseColor(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.LICENSE_COLOR, licenseColor, Byte.class));
                            carAccessRecordDto.setCarType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_TYPE, carType, Byte.class));

                            carAccessRecordDto.setOutOrIn(attrOfIntelligentEntranceGuard == null ? null : attrOfIntelligentEntranceGuard.getOutOrIn());

                            carAccessRecordDto.setSnapImages(StringUtils.isNotBlank(snapImage) ? JacksonUtils.toJsonString(new String[]{snapImage}) : null);
                            carAccessRecordDto.setAccessTime(StringUtils.isNotBlank(accessTime) ? DateUtils.parse(accessTime, DateUtils.FormatType.COMMON) : null);
                            return carAccessRecordDto;
                        }).filter(o -> o != null).collect(Collectors.toList());

                        carAccessRecordDtos.addAll(list);
                    }
                } catch (Exception e) {
                    logger.error("解析车辆出入数据出错", e);
                }
            }
        }
        carAccessRecordService.saveBatch(carAccessRecordDtos);
        successCount = carAccessRecordDtos.size();
        return Response.error("导入数据完成 总数:" + totalCount + " 成功数:" + successCount);
    }

    /**
     * 导出记录 carAccessRecord:exportExcel
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "carAccessRecord:exportExcel")
    @Operation(summary = "导出车辆出入记录")
    @Log(express = "导出车辆出入记录")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<MongoCarAccessRecordDto> result = PageFetchKit.fetchAll(r -> carAccessRecordService.queryList(r), request.getParams());

        String[] headers = new String[]{"所属小区", "设备名称", "车牌号", "车辆颜色", "车辆类型", "进出方式", "抓拍照片", "抓拍录像", "访问时间"};
        List<String[]> dataList = new ArrayList<>();
        for (MongoCarAccessRecordDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageDto().getName();
            item[1] = data.getDeviceName();
            item[2] = DesensitizedUtil.carLicense(data.getLicense());
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getLicenseColor() + "");
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CAR_TYPE, data.getCarType() + "");
            item[5] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.OUT_IN_TYPE, data.getOutOrIn() + "");
            item[6] = data.getSnapImages();
            item[7] = data.getSnapVideoes();
            item[8] = data.getAccessTime() != null ? DateUtils.format(data.getAccessTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "车辆出入记录", headers, dataList, "车辆出入记录");

    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "carAccessRecord:list")
    @Operation(summary = "车辆访问记录的分页查询列表")
    public Response<Page<MongoCarAccessRecordDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));


        String startTime = request.getString(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft());
        String endTime = request.getString(SystemConstants.TIME_SLOT_KEY_PAIR.getRight());

        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            if (Objects.requireNonNull(DateUtils.parse(endTime, DateUtils.FormatType.COMMON)).getTime()
                    - Objects.requireNonNull(DateUtils.parse(startTime, DateUtils.FormatType.COMMON)).getTime() > 1000 * 60 * 60 * 24 * 32L) {
                return Response.error("最长记录不能超过30天");
            }
        } else {
            request.put(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft(), DateUtils.format(DateUtil.offsetDay(new Date(), -7), DateUtils.FormatType.COMMON));
            request.put(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft(), DateUtils.format(new Date(), DateUtils.FormatType.COMMON));
        }

        super.fillAuthorityData(request.getParams());
        int total = carAccessRecordService.queryTotal(request.getParams());

        List<MongoCarAccessRecordDto> list = null;
        if (total > 0) {
            list = carAccessRecordService.queryList(request.getParams());
            for (MongoCarAccessRecordDto carAccessRecordDto : list) {
                carAccessRecordDto.setLicense(DesensitizedUtil.carLicense(carAccessRecordDto.getLicense()));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<MongoCarAccessRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<MongoCarAccessRecordDto>>ok().wrap(page);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "carAccessRecord:info")
    @Operation(summary = "查询单条车辆访问记录")
    public Response<MongoCarAccessRecordDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (carAccessRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        MongoCarAccessRecordDto carAccessRecordDto = carAccessRecordService.selectById(id);

        return Response.<MongoCarAccessRecordDto>ok().wrap(carAccessRecordDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "carAccessRecord:edit")
    @Operation(summary = "保存单条车辆访问记录")
    public Response<Object> save(@RequestBody @Validated MongoCarAccessRecordDto carAccessRecordDto) {

        //填充基础数据
        fillSaveCommonData(carAccessRecordDto);

        carAccessRecordService.save(carAccessRecordDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "carAccessRecord:delete")
    @Operation(summary = "批量删除存在的车辆访问记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (carAccessRecordService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        carAccessRecordService.deleteBatch(ids);

        return Response.ok();
    }
}
